package com.samecity.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/3/17 0017.
 */

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;
    private BaseResp resp = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      //  api = WXAPIFactory.createWXAPI(this, KeepData.APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        finish();
    }

    @Override
    public void onResp(BaseResp baseResp) {
        String result = "";
        if (resp != null) {
            resp = baseResp;
        }
        if (baseResp.getType()== ConstantsAPI.COMMAND_PAY_BY_WX){
            if (baseResp.errCode==0){
                Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "支付失败，请重试", Toast.LENGTH_SHORT).show();
            }
        }

        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                SendAuth.Resp sendAuthResp  = (SendAuth.Resp) baseResp;
                if (sendAuthResp!=null){
                    String Code = sendAuthResp.code;
                    getAccess_token(Code);
                }

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "发送取消";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "发送被拒绝";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
            default:
                result = "发送返回";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
        }
    }


    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code 请求码
     */
    private void getAccess_token(final String code) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
              //          + KeepData.APP_ID
                        + "&secret="
         //               + KeepData.WX_LOGIN_STATE
                        + "&code="
                        + code
                        + "&grant_type=authorization_code";

                OkHttpClient okHttpClient = new OkHttpClient();
                final okhttp3.Request request = new okhttp3.Request.Builder()
                        .url(path)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }
                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                            if (!response.body().toString().equals("")){
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(response.body().toString());
                                    if (jsonObject!=null){
                                        String openid = jsonObject.getString("openid").toString().trim();
                                        String access_token = jsonObject.getString("access_token").toString().trim();
                                        getUserMesg(access_token, openid);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                    }
                });

             /*   try {
                    JSONObject jsonObject = JsonUtils.initSSLWithHttpClinet(path);// 请求https连接并得到json结果
                    if (null != jsonObject) {
                        String openid = jsonObject.getString("openid").toString().trim();
                        String access_token = jsonObject.getString("access_token").toString().trim();
                        getUserMesg(access_token, openid);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }*/
            }
        }).start();

    }

    /**
     * 获取微信的个人信息
     *
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;


        OkHttpClient okHttpClient = new OkHttpClient();
        final okhttp3.Request request = new okhttp3.Request.Builder()
                .url(path)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (!response.body().toString().equals("")){
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response.body().toString());
                        if (jsonObject!=null){
                     //       KeepData.WX_NICK_NAME  = jsonObject.getString("nickname");
                    //        KeepData.WX_SEX = Integer.parseInt(jsonObject.get("sex").toString());
                      //      KeepData.WX_HEAD = jsonObject.getString("headimgurl");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

       /* try {
            JSONObject jsonObject = JsonUtils.initSSLWithHttpClinet(path);// 请求https连接并得到json结果
            if (null != jsonObject) {
                String nickname = jsonObject.getString("nickname");
                int sex = Integer.parseInt(jsonObject.get("sex").toString());
                String headimgurl = jsonObject.getString("headimgurl");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        return;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }



}
